<template>
	<div class="v-tree">
		<el-input v-if="filter" v-model="search" :placeholder="placeholder" class="v-tree-input" clearable />
		<el-tree ref="treeRef" :data="data" :props="defaultProps" :filter-node-method="filterNode" @node-click="nodeClick"
			highlight-current></el-tree>
	</div>
</template>

<script setup>
import { ref, shallowRef, watch } from "vue"
import { getAxios } from "/axios"
import { findPinYin } from "/plugins/pinyin"

const props = defineProps({
	placeholder: {
		type: String,
		default: "请搜索...",
	},
	url: {
		type: String,
	},
	data: {
		type: Array,
	},
	label: {
		type: String,
		default: "name",
	},
	value: {
		type: String,
		default: "id",
	},
	children: {
		type: String,
		default: "children",
	},
	filter: {
		type: Boolean,
		default: true,
	},
	haveAll: {
		type: Boolean,
		default: true,
	},
})

const emits = defineEmits(["click"])
const treeRef = shallowRef()

const search = shallowRef("")
const defaultProps = {
	children: props.children,
	label: props.label,
}
const data = ref(props.data || [])

const filterNode = (value, data) => {
	if (!value) return true
	return findPinYin(data[props.label], value)
}
function nodeClick(data) {
	if (props.value) {
		emits("click", data[props.value])
	} else {
		emits("click", data)
	}
}

watch(search, value => {
	treeRef.value?.filter(value)
})

if (props.url) {
	getAxios(props.url).then(result => {
		if (props.haveAll) {
			result.unshift({
				[props.value]: "",
				[props.label]: "全部",
			})
		}
		data.value = result
	})
}
</script>

<style lang="scss" scoped>
.v-tree-input {
	width: 100%;
	margin-bottom: 10px;
}
</style>
